package com.kc.common.utils;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;
import com.alibaba.fastjson.JSON;
import com.kc.common.enums.JpushMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author zhangshuo
 * @version 1.0
 * @date 2020/10/12
 */
@Slf4j
@Component
public class JPushUtil {
    private static final String APPKEY = "53755f3677eee76ee5afaffe";
    private static final String SECRET = "5376d0786b77311958548ccf";
    private static final boolean PROD = false;

    private static JPushClient jpushClient = new JPushClient(SECRET, APPKEY, null, ClientConfig.getInstance());
    private final static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 指定用户极光推送
     *
     * @param message
     * @param extras
     * @param token
     * @return
     */
    public static void push(String message, Map<String, String> extras, String... token) {
        try {

            PushPayload payload = pushAllNotify(message, extras, token);
            PushResult result = jpushClient.sendPush(payload);
            log.info(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 指定用户极光定时推送
     *
     * @param message
     * @param extras
     * @param token
     * @return
     */
    public static void schedulePush(String title, String message, Map<String, String> extras, LocalDateTime time, String... token) {
        try {

            PushPayload push = pushAllNotify(message, extras, token);
            ScheduleResult result = jpushClient.createSingleSchedule(title, dtf.format(time), push);
            log.info(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 全平台指定用户推送
     *
     * @param message
     * @param extras
     * @param token
     * @return
     */
    public static PushPayload pushAllNotify(String message, Map<String, String> extras, String... token) {
        PushPayload.Builder payload = PushPayload.newBuilder()
                .setPlatform(Platform.all());
        payload.setAudience(StringUtils.isEmpty(token) ? Audience.all() : Audience.alias(token));
        payload.setNotification(Notification.newBuilder().setAlert(message)
                .addPlatformNotification(IosNotification.newBuilder().addExtras(extras).build())
                .addPlatformNotification(AndroidNotification.newBuilder().addExtras(extras).build())
                .build()
        );
        if (PROD) payload.setOptions(Options.newBuilder().setApnsProduction(true).build());
        return payload.build();
    }

    /**
     * 指定平台全用户推送
     * time不为空--定时推送
     *
     * @param flag（1:Android,2:IOS,3:全部）
     * @param message
     * @return
     */
    public static void pushFlag(Integer flag, String title, String message, LocalDateTime time) {
        try {

            Map<String, String> extras = new HashMap<>();
//            String to = JPushEnum.MESSAGE_SYSTEM.getCode();
            PushPayload payload = JpushMessage.ALL_PLATFORM.getCode().equals(flag) ? pushAllNotify(message, extras) :
                    JpushMessage.IOS.getCode().equals(flag) ? pushIosNotify(message, extras) :
                            pushAndroidNotify(message, extras);
            //时间为空则为正常推送
            if (time == null) {
                PushResult result = jpushClient.sendPush(payload);
                log.info(JSON.toJSONString(result));
            }
            //时间不为则为定时推送
            else {
                ScheduleResult result = jpushClient.createSingleSchedule(title, dtf.format(time), payload);
                log.info(JSON.toJSONString(result));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 安卓全平台推送
     *
     * @param message
     * @param extras
     * @return
     */
    private static PushPayload pushAndroidNotify(String message, Map<String, String> extras) {
        PushPayload.Builder payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setNotification(
                        Notification.newBuilder().addPlatformNotification(
                                AndroidNotification.newBuilder().setAlert(message).addExtras(extras).build()
                        ).build()
                );
        return payload.build();
    }

    /**
     * ios全平台推送
     *
     * @param message
     * @param extras
     * @return
     */
    private static PushPayload pushIosNotify(String message, Map<String, String> extras) {
        PushPayload.Builder payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(
                        Notification.newBuilder().addPlatformNotification(
                                IosNotification.newBuilder().setAlert(message).addExtras(extras).build()
                        ).build()
                );
        if (PROD) payload.setOptions(Options.newBuilder().setApnsProduction(true).build());
        return payload.build();
    }

    /**
     * 指定用户极光透传
     *
     * @param message
     * @param extras
     * @param token
     * @return
     */
    public static void transmit(String title, String message, Map<String, String> extras, String... token) {
        try {

            PushPayload payload = sendAllPush(title, message, extras, token);
            PushResult result = jpushClient.sendPush(payload);
            log.info(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 全平台指定用户极光透传
     *
     * @param title   标题
     * @param message 消息内容
     * @param extras  app跳转表识
     * @return
     */
    public static PushPayload sendAllPush(String title, String message, Map<String, String> extras, String... token) {
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(StringUtils.isEmpty(token) ? Audience.all() : Audience.alias("token"))
                .setMessage(Message.newBuilder()
                        .setMsgContent(message)
                        .setTitle(title)
                        .addExtras(extras)
                        .build())
                .build();
        if (PROD)
            payload.resetOptionsApnsProduction(true);
        return payload;
    }


    /**
     * 指定平台全用户透传
     *
     * @param flag（1:Android,2:IOS,3:全平台）
     * @param message
     * @return
     */
    public static void transmitFlag(String flag, String title, String message) {
        try {

            Map<String, String> extras = new HashMap<>();
//            String to = JPushEnum.MESSAGE_SYSTEM.getCode();
            PushPayload payload = JpushMessage.ALL_PLATFORM.getCode().equals(flag) ? sendAllPush(title, message, extras) :
                    JpushMessage.IOS.getCode().equals(flag) ? sendIosPush(title, message, extras) :
                            sendAndroidPush(title, message, extras);
            PushResult result = jpushClient.sendPush(payload);
            log.info(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 安卓全平台透传
     *
     * @param message
     * @param extras
     * @return
     */
    private static PushPayload sendAndroidPush(String title, String message, Map<String, String> extras) {
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setMessage(Message.newBuilder()
                        .setMsgContent(message)
                        .setTitle(title)
                        .addExtras(extras)
                        .build()).build();
        return payload;
    }

    /**
     * ios全平台透传
     *
     * @param message
     * @param extras
     * @return
     */
    private static PushPayload sendIosPush(String title, String message, Map<String, String> extras) {
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setMessage(Message.newBuilder()
                        .setMsgContent(message)
                        .setTitle(title)
                        .addExtras(extras)
                        .build()).build();
        if (PROD) payload.resetOptionsApnsProduction(true);
        return payload;
    }
}
